package com.zss.dao.imp;

import com.zss.dao.BaseAdminDao;
import com.zss.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

public class AdminDaoMysql implements BaseAdminDao {
    private static final String SQL_UPDATE_LOGIN_TIME = "UPDATE EADMIN SET LOGINTIME = ?,LOGINIP = ? WHERE USERNAME =?";
    private static final String SQL_LOGIN = "SELECT ID FROM EADMIN WHERE USERNAME =? AND PASSWORD=?";

    /**
     * 根据用户登录更新登录时间
     *
     * @param username
     * @param date
     * @param ip
     */
    @Override
    public void updateLonginTime(String username, Date date, String ip) {
        //获取连接
        Connection conn = DruidUtil.getConnection();

        //预编译
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            //传参数
            state.setDate(1, new java.sql.Date(date.getTime()));
            state.setString(2, ip);
            state.setString(3, username);
            //执行sql语句
            state.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            //释放资源
            DruidUtil.close(conn, state, null);
        }


    }

    /**
     * 根据账号密码登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public boolean login(String username, String password) {
        Connection conn = DruidUtil.getConnection();
        //预编译
        PreparedStatement state = null;
        ResultSet rs = null;
        try {
            state = conn.prepareStatement(SQL_LOGIN);
            //传参数

            state.setString(1, username);
            state.setString(2, password);
            //执行sql语句
            rs = state.executeQuery();
            //将结果放回
            return rs.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DruidUtil.close(conn, state, null);
        }
        return false;
    }
}
